<template>

  <div>
    <!--  弹出方向改为全局的用户可配置 vue store 中  -->
    <!--  最大最小百分比设置 -->
    <!--        -->
    <el-drawer
      :before-close="handleClose"
      :show-close="false"
      :visible.sync="listShow"
      :withHeader="false"
      ref="drawer"
      size="60%"
    >

      <!--   必须要做成滚动加载的table,   -->
      <!--      title="产品物料列表"    -->
      <!--     form  > row > col > formItem > input ...     -->
      <el-card style="margin: 10px">
        <div slot="header" style="display: flex;justify-content: space-between;align-items: center">
          <span>{{`全部${linkTo}列表`}}</span>
          <AButton
            :loading="loading"
            @click="$refs.drawer.closeDrawer()"
            type="primary">
            {{`关闭并保存${linkTo}`}}
            <i class="el-icon-circle-close"></i>
          </AButton>
        </div>

        <!--   用户当前选择的     -->
        <!--        <div>-->
        <!--          <el-tag/>-->
        <!--        </div>-->

        <el-alert
          :closable="false"
          show-icon
          title="点击🎶来配置组件"
          type="success"
        />

        <el-checkbox-group v-model="proxyCheckedItemIds">

          <!--      v-loading="listLoading"    -->
          <azure-dynamic-table
            :column-des-objs="columnDesObjs"
            :data="allProductTableData"
            :showSeq="true"
            empty-text="暂无组件可配置 🎁🎁🎁🎁🎶😎🤣"
            height="72vh"
          >

            <template #tableHead>
              <el-popover
                title="请根据需要填写查找条件,完成后点击搜索🎉😉✔🐱‍🏍👍👌"
                trigger="click"
                width="600">
                <el-form
                  :label-width="labelWidth"
                  :model="searchFormData" ref="searchDataForm" style="margin-top: 30px;">
                  <show-more @getData="reGetData" @resetSearch="resetSearch">
                    <template slot="main">

                      <el-row :gutter="globalGutter">
                        <el-col v-bind="globalGrid2">
                          <el-form-item label="产品名称" prop="name">
                            <el-input
                              clearable
                              placeholder="请输入产品名称" size="small"
                              v-model="searchFormData.name">
                              <el-button icon="el-icon-toilet-paper" slot="append"></el-button>
                            </el-input>
                          </el-form-item>
                        </el-col>
                        <el-col v-bind="globalGrid2">
                          <el-form-item label="产品编码" prop="code">
                            <el-input
                              clearable
                              placeholder="请输入产品编码" size="small"
                              v-model="searchFormData.code">
                              <el-button icon="el-icon-s-grid" slot="append"></el-button>
                            </el-input>
                          </el-form-item>
                        </el-col>
                      </el-row>

                      <el-row :gutter="globalGutter">
                        <el-col v-bind="globalGrid2">
                          <el-form-item label="产品分类" prop="categoricalId">
                            <product-categorical-select
                              v-model="searchFormData.categoricalId"
                            />
                          </el-form-item>
                        </el-col>
                        <el-col v-bind="globalGrid2">
                          <el-form-item label="打印类型" prop="printTypeId">
                            <product-print-type v-model="searchFormData.printTypeId"/>
                          </el-form-item>
                        </el-col>
                      </el-row>

                      <el-row :gutter="globalGutter">
                        <el-col v-bind="globalGrid2">
                          <el-form-item label="输出类型" prop="shopType">
                            <shop-type-select
                              v-model="searchFormData.shopType"/>
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </template>

                  </show-more>
                </el-form>

                <el-button
                  icon="el-icon-search"
                  round
                  size="mini"
                  slot="reference"
                  type="primary">按条件搜索{{linkTo}}
                </el-button>

              </el-popover>
            </template>
            <infinite-loading
              :identifier="infiniteId"
              @infinite="infinite"
              force-use-infinite-wrapper=".el-table__body-wrapper"
              slot="azure">
              <div class="no-more" slot="no-more">
                {{searchFormData.page >=10 ? '翻了这么多页了休息一下吧😎😎.....' : `没有更多${linkTo}了😜🎶🤣🎉🎁..... (～￣▽￣)～`}}
              </div>
              <div class="no-more" slot="no-results">
                暂无结果 Ծ‸Ծ
              </div>
              <div class="no-more" slot="error">
                出错了 (╯‵□′)╯︵┻━┻😁😒🎁😢🤞🐱‍👤🐱‍💻🐱‍🐉🐱‍👓🐱‍🚀
              </div>
            </infinite-loading>

            <template slot="operator" slot-scope="{scope:{row,$index}}">
              <el-checkbox-button :label="row.partId">
                配置{{linkTo}}🎶
              </el-checkbox-button>
            </template>

          </azure-dynamic-table>
        </el-checkbox-group>
      </el-card>
    </el-drawer>

  </div>
</template>

<script>
  import AButton from '@/components/ATheFridayClub/AButton'
  import AzureDynamicTable from '@/components/ATheFridayClub/mDynamicTable/AzureDynamicTable'
  import { MaterialItemGetAllPage, PageQueryProduct } from '@/api/productInformation'
  import { ERR_OK } from '@/utils/commons'
  import { objFirstKeyLowerCase } from '@/utils/fridayClub/objectUtil'
  import { productTypesEnum } from '@/enums/product'
  import { productBaseCols } from '@/views/baseproduct/mixins/productUtil'
  import { materialFactory, transformMaterialItemVO } from '@/views/baseproduct/components/halfComponent/materialUtil'
  import { deepClone } from '@/utils'
  import productMixin from '@/views/baseproduct/components/product/productMixin'
  import { setCol2Hidden } from '@/utils/fridayClub/tableUtil'
  import InfiniteLoading from 'vue-infinite-loading'
  import ShowMore from '@/components/ATheFridayClub/ShowMore'
  import layoutMixin from '@/mixins/layoutMixin'
  import ProductCategoricalSelect from '@/components/ATheFridayClub/businessSelect/product/productCategoricalSelect'
  import ProductPrintType from '@/components/ATheFridayClub/businessSelect/print/productPrintType'
  import ShopTypeSelect from '@/components/ATheFridayClub/businessSelect/product/shopTypeSelect'
  import ProductSelect from '@/components/ATheFridayClub/businessSelect/product/ProductSelect'
  import { dataStatusTypesEnum } from '@/enums/common'
  import form from '@/mixins/form'
  // 1 用来给产品配置的组件
  // 2 或者给套系配置产品
  //  c 2 c 目前还没有

  const columnDesObjs = Array.of(
    ...((Array.of(...productBaseCols)) |> (cols => setCol2Hidden(cols,
      // 'ProductId',
      // 'ProductTypeTxt',
      // 'ProductName',
      // 'Code',
      'CategoricalId',
      // 'ProductShopType',
      'ProductSize',
      'Describe',
      'SizeDetailId'
    )))
  )

  export default {
    name: 'ShowAllProductListDrawer',
    components: {
      ProductSelect,
      ShopTypeSelect,
      ProductPrintType,
      ProductCategoricalSelect,
      ShowMore,
      AzureDynamicTable,
      AButton,
      InfiniteLoading
    },
    mixins: [productMixin, layoutMixin, form],
    props: {

      tableData: {  //  外部已经选中的
        type: Array,
        default: () => (Array.of())
      },
      //    当前选中的材料ids
      checkedItemIds: {
        type: Array,
        default: () => ([])
      },
      modifyData: { //  因为修改配置信息要用
        type: Object,
        default: () => ({})
      },
      hasChange: {
        type: Boolean
      },
      submitBeforeCallback: {
        type: Function
      }
    },
    data() {
      return {
        columnDesObjs: Array.of(...columnDesObjs,
          // { label: '选择', key: 'check' }
          { label: '操作', key: 'operator', width: 160 }
        ),
        productTableList: [],
        listShow: false,
        listLoading: false,
        backTableData: Array.of(), //  备份的数据

        infiniteId: new Date().getTime(),
        allProductTableData: Array.of(),  //  全部的组件列表
        //  滚动加载相关
        searchFormData: {
          name: '', //  产品名

          code: '',//  产品编码
          productType: null,  //  el-select 匹配不到会显示一个奇怪的值,必须为null

          categoricalId: '',
          printTypeId: '',
          shopType: '',
          status: dataStatusTypesEnum['正常'],  //  默认传正常,不需要删除的

          page: 1,
          limit: 10
        },
        total: 0,
        loading: false,
        labelWidth: '80px',

        deleteItems: [] //  删除的条目
      }
    },
    // watch: {
    //   proxyProductType() {
    //     this.getData()    //  reset
    //   }
    // },
    computed: {
      proxyCheckedItemIds: {
        get() {
          return this.checkedItemIds
        },
        set(checkedIds) {
          console.log(checkedIds)
          const checkedItems =
            this.allProductTableData.filter(v => checkedIds.includes(v.partId))
          //  logger props in arr
          //  table scroll
          //  封装该业务功能组件 减少灵活度
          //  算法需要改进
          // all = old row + new row
          const { latestResultData, deleteData } = Array.of(...this.tableData, ...checkedItems
              .filter(({ partId }) => !(this.proxyCheckedItemIds.includes(partId)))
            // |> debugLogger('all checked')
          ).reduce((acc, cur) => {
            const { partId } = cur
            const changeProps = checkedIds.includes(partId) ? 'latestResultData' : 'deleteData'
            return {
              ...acc, [changeProps]: [...acc[changeProps], cur]
            }
          }, {
            latestResultData: [], //  计算后还剩余的
            deleteData: []  //  需要删除的
          })

          //  更新table数据
          this.updateTableData(latestResultData)

          this.deleteItems = deleteData
          //  派发事件,里面有最终的结果items 和 删除的items
          // this.$emit('checkedItemListChange', { latestResultData, deleteData })

          // this.hasChange = true
          // this.$emit('checkedItemIdsChange',
          //   checkedIds,
          //   this.tableData.filter(v => checkedIds.includes(v.MaterialItemID))
          // )
        }
      }
    },

    methods: {

      //  滚动加载
      infinite($state) {
        console.log('infinite')
        this.getData({ $state })
      },

      //  通过ref给外部调用
      show() {
        this.listShow = true
        console.log('modifyData >>>>>>>>>')
        console.log(this.modifyData)
        //  保存一份原始数据指针,可以深拷贝  backTableData

        this.backTableData = deepClone(this.tableData)
      },

      updateTableData(retTableData) {
        this.$emit('update:tableData', retTableData)
      },

      resetData() {
        this.updateTableData(this.backTableData)
      },

      //  关闭前提示是否保存
      async handleClose(done) {
        //  调用 done 关闭窗口
        try {
          await this.$confirm('确认关闭并保存,点击取消放弃保存？')
          const finalize = () => {
            this.loading = false
          }
          const resolve = () => {
            done()
            this::finalize()
          }
          const reject = () => {
            this.resetData()
            this::finalize()
          }
          this.loading = true
          const { deleteItems } = this

          this.submitBeforeCallback({ resolve, reject, deleteItems })
        } catch (err) {
          this.resetData()
          console.log(err)
          if (err === 'cancel') {
            done()
          }
        }
      },
      reGetData() {
        this.initAllProductListTable()
      },
      resetSearch() {
        this.resetForm('searchDataForm')
        this.initAllProductListTable()
      },
      initAllProductListTable() {
        this.searchFormData.page = 1
        this.allProductTableData = Array.of()
        this.infiniteId++
      },
      //  查询全部的
      async getData({ $state } = {}) {
        this.listLoading = true
        const {
          proxyProductType,
          searchFormData: {
            page, limit
          }
        } = this
        //  需要过滤的,日后添加form表单
        // const {
        //   name, code, categoricalId,
        //   printTypeId, shopType, status
        // } = objFirstKeyLowerCase(this.modifyData)
        try {
          // pageSize: limit,
          //   pageNum: page,
          const { Code, Result } = await PageQueryProduct({
            ...this.searchFormData,
            productType: productTypesEnum.getProp(proxyProductType, 'config2MappingValue'),
            pageSize: limit, pageNum: page
            //  其他的查询项
            // name, code, categoricalId, printTypeId, shopType, status
          })
          if (Code === ERR_OK) {
            const { CurrentPage, RecordCount, Rows } = Result
            this.searchFormData.page = CurrentPage
            this.searchFormData.total = RecordCount
            this.allProductTableData.push(...Rows.map(v => {
              const { ProductId, ...other } = v
              return ({
                ...other, partId: ProductId, ProductId
              })
            }))

            $state.loaded()

            if (CurrentPage * this.searchFormData.limit < RecordCount) {
              this.page++
            } else {
              $state.complete()
            }
          } else {
            $state.error()
          }
        } catch (e) {
          console.log(e)
          $state.error()
        } finally {
          this.listLoading = false
        }

      }

    }
  }
</script>

<style lang="scss" scoped>

  //  无限滚动加载
  .no-more {
    margin: 10px auto;
  }
</style>
